package com.hxexp.weixin.mvc.common.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hxexp.weixin.common.config.DeployConfig;
import com.hxexp.weixin.common.exception.ServiceException;
import com.hxexp.weixin.common.zip.ZipUtils;
import com.hxexp.weixin.mvc.common.service.SNSOauth2Service;
import com.qq.weixin.constant.APIConstant;
import com.qq.weixin.constant.AppDevConstant;

/**
 * 网页授权controller
 *
 * @author li.jiang
 *
 */
@Controller
@RequestMapping(value = "/oauth2")
public final class SNSOauth2Controller {
    private static final Logger LOGGER = LoggerFactory.getLogger(SNSOauth2Controller.class);
    @Autowired
    private SNSOauth2Service snsOauth2Service;
    @Autowired
    private DeployConfig deployConfig;

    /**
     * 获取openid并写入cookie
     *
     * @param code
     *            换取access_token的票据
     * @param returnURL
     *            跳转链接地址
     * @param response
     *            http响应
     * @return
     */
    @RequestMapping(value = "/openid")
    @ResponseBody
    public String getOpenid(String code, String returnURL, HttpServletResponse response) {
        String returnUrl = ZipUtils.ungzip(returnURL);

        LOGGER.debug("openid写入cookie后的返回链接：returnURL={}", returnUrl);

        if (!StringUtils.isEmpty(returnUrl)) {
            try {
                String openid = snsOauth2Service.setOpenid2Cookie(code, response);
                // 返回链接不含参数的情况
                if (returnUrl.indexOf("?") == -1) {
                    returnUrl = String.format("%s?openid=%s", returnUrl, openid);
                } else {
                    returnUrl = String.format("%s&openid=%s", returnUrl, openid);
                }

                response.sendRedirect(returnUrl);
            } catch (ServiceException e) {
                LOGGER.error("获取openid并写入cookie时发生异常！", e);
            } catch (IOException e) {
                LOGGER.error("获取openid后重定向发生异常！", e);
            }
        }
        return "";
    }

    /**
     * 处理微信网页认证请求
     *
     * @param redirectURL
     *            重定向URL
     * @param request
     *            http请求
     * @param response
     *            http响应
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/authorize")
    @ResponseBody
    public String handleAuthorize(String redirectURL, HttpServletRequest request, HttpServletResponse response) {
        if (StringUtils.isEmpty(redirectURL)) {
            return "redirectURL参数不能为空！";
        }
        // 获取openid并写入cookie的URL
        String oauth2OpenidURL = String.format("http://%s%s%s", request.getHeader("Host"), request.getContextPath(), APIConstant.OAUTH2_OPENID_URI);

        String returnURL = ZipUtils.gzip(redirectURL);
        oauth2OpenidURL = String.format("%s?returnURL=%s", oauth2OpenidURL, returnURL);
        try {
            oauth2OpenidURL = URLEncoder.encode(oauth2OpenidURL, "UTF-8"); // URL转码:转义特殊字符

            // 重定向到微信网页认证URL，认证通过后返回到原来的页面
            response.sendRedirect(
                    String.format(APIConstant.AUTHORIZE_URL_TEMPLATE, AppDevConstant.getAppId(deployConfig.getDeployEnvironment()), oauth2OpenidURL));
        } catch (UnsupportedEncodingException e) {
            LOGGER.error("字符编码异常！", e);
        } catch (IOException e) {
            LOGGER.error("IO异常！", e);
        }
        return "";
    }
}
